import deepcopy from "deepcopy";
export default function editorEvent(
  dragItem,
  data,
  lastCheckItem,
  ctx,
  showPreview
) {
  const onPreview = () => {
    //渲染一个 <ElDialog>,dialog内容是 <Preview>
    for (let item of data.value.blocks) {
      if (!item.propName) {
        ElMessage({
          type: "error",
          message: `请输入${item.label}propName`,
        });
        return;
      }
    }
    showPreview.value = true; // 打开对话框
  };
  //点击config-left向editor-form区域添加数据
  const addData = (item) => {
    let newItem = deepcopy(item);
    newItem.keyName = Math.random().toString(36).substr(2);
    newItem.propName = "";
    if (lastCheckItem.value) {
      let index = data.value.blocks.findIndex(
        (item) => item.keyName == lastCheckItem.value.keyName
      );
      data.value.blocks.splice(index + 1, 0, newItem);
    } else {
      data.value.blocks.push(newItem);
      //   console.log("插入",newItem);
    }
  };

  /* 
    判断propName唯一性
    */
  const isOnlyProp = (data, newItem) => {
    let arr = data.value.propNames.filter((item) => {
      return item.propName == newItem.propName;
    });
    if (arr.length == 1 && arr[0].keyName != newItem.keyName) {
      return false;
    }
    return true;
  };

  /* 记录唯一propName-keyName对象数组 */
  const recordPropName = (data, newItem) => {
    let arr = data.value.propNames.map((item) => item.keyName);
    let keyValue = {
      keyName: newItem.keyName,
      propName: newItem.propName,
    };
    if (!arr.includes(newItem.keyName)) {
      data.value.propNames.push(keyValue);
    } else {
      let index = data.value.propNames.findIndex(
        (item) => item.keyName == newItem.keyName
      );
      data.value.propNames[index] = keyValue;
    }
  };

  //删除data.blocks中的item
  const removeFromBlocks = (index) => {
    let item = data.value.blocks[index];
    let innerIndex = data.value.propNames.findIndex(
      (inner) => inner.keyName == item.keyName
    );
    data.value.propNames.splice(innerIndex, 1);
    data.value.blocks.splice(index, 1);
    lastCheckItem.value = null;
  };

  //改变data的值
  const changeItem = (newItem) => {
    //替换data.value['blocks']中keyName 等于newItem.keyName的item
    data.value.blocks.forEach((item, index) => {
      if (item.keyName === newItem.keyName) {
        // console.log(123, newItem);
        //验证data.value.propNames中不包含执行以下，否则提示属性名重复
        if (!newItem.propName) {
          newItem.propName = "k" + deepcopy(newItem.keyName);
        }

        if (!isOnlyProp(data, newItem)) {
          ElMessage({
            type: "error",
            message: `属性名${newItem.propName}重复`,
          });
          return;
        }

        data.value.blocks[index] = newItem;
        // console.log("改变data.value.blocks：", newItem);

        recordPropName(data, newItem);
        // console.log(789,data.value.propNames);
      }
    });
  };

  //全部填写
  const isCanSubmit = () => {
    console.log("isCanSubmit:", data.value.blocks);
    let flag = true;
    for (const [index,item] of data.value.blocks.entries()){

      if (!item.propName) {
        flag = false;
        ElMessage({
          type: "error",
          message: `请将组件${index+1}填写完整并保存`,
        });
        return flag;
      }
    }
    return flag;
  };

  //提交
  const onSubmit = () => {
    // console.log(123, JSON.stringify(data.value));

    if(isCanSubmit()){
      ElMessageBox.confirm("是否提交" + JSON.stringify(data.value), "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let fieldsData = data.value.blocks.map((item, index) => {
          return {
            fieldName: item.propName,
            fieldType: "varchar",
            fieldLength: 100,
            need: item.mustFill ? true : false,
            notes: item.label,
            decimalPoint: 0,
            orderNum: index + 1,
          };
        });
        // axios
        //   .post("/v1/demo/lowCode/designTable", {
        //     tableId: data.value.tableId,
        //     fields: fieldsData,
        //     styleJson: JSON.stringify(data.value),
        //   })
        //   .then((res) => {
        //     ElMessage({
        //       type: "success",
        //       message: "提交成功",
        //     });
        //     ctx.emit("closeEditor", null);
        //   })
        // .catch((err) => {});
      });
    }
  };

  const onInput = () => {
    ElMessageBox.prompt("请输入本平台生成的JSON字符串", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      inputErrorMessage: "Invalid Email",
    })
      .then(({ value }) => {
        ElMessage({
          type: "success",
          message: `导入成功`,
        });
        data.value = JSON.parse(value);
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "请检查JSON格式",
        });
      });
  };

  const onClose = () => {
    ElMessageBox.confirm("是否关闭", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      ctx.emit("closeEditor", null);
    });
  };

  return {
    addData,
    isOnlyProp,
    recordPropName,
    removeFromBlocks,
    changeItem,
    onInput,
    onClose,
    onSubmit,
    onPreview,
  };
}
